package com.xiashitech.agent.service;

import com.xiashitech.agent.cache.data.CacheData;
import com.xiashitech.agent.cache.data.CacheSync;
import com.xiashitech.agent.grpc.XsUserClient;
import com.xiashitech.agent.utils.XiashiGrpcUtil;
import com.xiashitech.agent.utils.HttpUtil;
import com.xiashitech.agent.utils.JsonUtil;
import com.xiashitech.interfaces.agent.dto.AgentConfigDTO;
import com.xiashitech.interfaces.apiservice.dto.user.UserInfoRequest;
import com.xiashitech.interfaces.apiservice.dto.user.UserInfoResponse;

public class UserInfoService {
    public static UserInfoResponse retrieveUserInfo(UserInfoRequest userRequest) {
        CacheData cacheData = CacheSync.getInstance().getCacheData(userRequest);
        if(cacheData != null && !cacheData.isFresh()) {
            return (UserInfoResponse)cacheData.getReturnValue();
        }
        if(XiashiGrpcUtil.useGrpc()) {
            CacheSync.getInstance().init(UserInfoService.class, "retrieveUserInfo", userRequest, null);
            XsUserClient.getClient().retrieveUserInfoGRPC(userRequest);
        } else {
            String param = JsonUtil.convertObjectToString(userRequest);
            String response = HttpUtil.doPost(AgentConfigDTO.getConfig().getUserinfoservice(), param, "application/json;charset=UTF-8");
            if (response != null && !response.isEmpty() && JsonUtil.isJson(response)) {
                UserInfoResponse userResponse = JsonUtil.convertStringToObject(response, UserInfoResponse.class);
                if (userResponse.getResult()) {
                    if (cacheData == null) {
                        CacheSync.getInstance().init(UserInfoService.class, "retrieveUserInfo", userRequest, userResponse);
                    }
                    return userResponse;
                } else {
                    CacheSync.getInstance().init(UserInfoService.class, "retrieveUserInfo", userRequest, null);
                }
            } else {
                CacheSync.getInstance().init(UserInfoService.class, "retrieveUserInfo", userRequest, null);
            }
        }
        return null;
    }
}
